<!doctype html>
<html>
<head>
    <link rel="stylesheet" href="/static/node_modules/xterm/css/xterm.css"/>
    <script src="/static/node_modules/xterm/lib/xterm.js"></script>
    <style>
        #box {
            width: 300px;
            height: 300px;
            border: 1px dashed #000;
            position: absolute;
            top: 50%;
            left: 50%;
            margin: -150px 0 0 -150px;
            text-align: center;
            font: 20px/300px '微软雅黑';
            display: none;
            z-index: 10000;
        }
    </style>
</head>
<body>
{{ id }}
<div style="width: 100%;" id="terminal"></div>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
    var _off = true // 记录关闭点
    var w = Math.floor(window.innerWidth / 9)
    var h = Math.floor(window.innerHeight / 18.5)
    var term = new Terminal({
        rendererType: "canvas", //渲染类型
        rows: h, //行数
        cols: w,
        // cols: parseInt(_this.cols), // 不指定行数，自动回车后光标从下一行开始
        convertEol: true, //启用时，光标将设置为下一行的开头
        scrollback: 50, //终端中的回滚量
        disableStdin: false, //是否应禁用输入。
        cursorStyle: "underline", //光标样式
        cursorBlink: true, //光标闪烁
        theme: {
            foreground: "#7e9192", //字体
            background: "#002833", //背景色
            cursor: "help", //设置光标
            lineHeight: 16
        }
    });
    term.open(document.getElementById("terminal"))
    var ws = new WebSocket("ws://" + window.location.host + "/ws/host/ssh/{{ data.host }}/{{data.openid}}/{{ data.operator }}?w=" + w + "&h=" + h)
    ws.onopen = function () {
        // Web Socket 已连接上，使用 send() 方法发送数据
        //  ws.send("发送数据");
        ws.send(JSON.stringify({"_W": w, "_H": h}))
    };
    ws.onmessage = function (evt) {
        console.log(JSON.parse(evt.data).code)
        if (JSON.parse(evt.data).code === 1007) {
            console.log('触发关闭')
            ws.close()
            _off = false
        }
        term.write(JSON.parse(evt.data).data)
    };
    ws.onclose = function () {
        // 关闭 websocket
        // alert("服务端断开连接.....");
        if (_off) {
            ws.close()
            _off = false
        }
    }
    term.onKey(e => {
        if (_off) {
            ws.send(e.key)
        }
    })
    // 尺寸改变事件
    window.onresize = function () {
        if (_off) {
            w = window.innerWidth
            h = window.innerHeight
            ws.send(JSON.stringify({"_W": w, "_H": h}))
        }
    }
</script>

</body>
</html>